const app = getApp();
const db = wx.cloud.database();
const _ = db.command; // 引入命令操作符

Page({
  data: {
    selectedDate: '',
    startDate: '',
    endDate: '',
    temperatureData: [],
    humidityData: [],
    co2Data: [],
    timeLabels: [],
    aiAdvice: '',
    predictionAdvice: '',
    adviceLoaded: false,
    predictionLoaded: false,
    greenhouseData: []
  },

  onLoad: function(options) {
    this.initDatePicker();
    this.loadGreenhouseData();
  },

  onShow: function() {
    this.loadGreenhouseData();
    this.generateAdvice();
  },

  initDatePicker: function() {
    const today = new Date();
    const year = today.getFullYear();
    const month = (today.getMonth() + 1).toString().padStart(2, '0');
    const day = today.getDate().toString().padStart(2, '0');
    
    this.setData({
      selectedDate: `${year}-${month}-${day}`,
      startDate: '2025-01-01',
      endDate: `${year}-${month}-${day}`
    });
  },

  onDateChange: function(e) {
    const selectedDate = e.detail.value;
    this.setData({
      selectedDate: selectedDate,
      adviceLoaded: false,
      predictionLoaded: false
    });
    
    this.loadGreenhouseData();
    this.generateAdvice();
  },

  loadGreenhouseData: function() {
    const selectedDate = this.data.selectedDate;
    console.log('selectedDate:', selectedDate);
    
    // 构造查询的日期范围（字符串格式，与数据库一致）
    const startStr = `${selectedDate}T00:00:00+08:00`;
    const endStr = `${selectedDate}T23:59:59+08:00`;
    
    console.log('startStr:', startStr);
    console.log('endStr:', endStr);

    db.collection('Greenhouse_Data')
      .where({
        // 使用正则表达式匹配日期字符串范围
        monitortime: db.RegExp({
          regexp: `^${selectedDate}`,
          options: 'i'
        })
      })
      .get()
      .then(res => {
        const filteredData = res.data;
        console.log('查询到的数据:', filteredData);
        
        if (filteredData.length === 0) {
          wx.showToast({
            title: '暂无该日期数据',
            icon: 'none'
          });
          return;
        }

        this.processDataForCharts(filteredData);
        this.setData({
          greenhouseData: filteredData
        });
      })
      .catch(err => {
        console.error('数据库查询失败', err);
        wx.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      });
  },

  processDataForCharts: function(data) {
    // 处理数据用于图表绘制
    const temperatureData = [];
    const humidityData = [];
    const co2Data = [];
    const timeLabels = [];
    
    console.log('处理前的数据长度:', data.length);
    
    // 按时间排序
    data.sort((a, b) => {
      // 直接比较字符串日期（格式相同，可直接按字典序排序）
      return a.monitortime.localeCompare(b.monitortime);
    });
    
    // 提取数据
    data.forEach(item => {
      // 将字符串日期转换为Date对象，以便格式化时间标签
      const time = new Date(item.monitortime);
      const hour = time.getHours();
      const minute = time.getMinutes();
      timeLabels.push(`${hour}:${minute < 10 ? '0' + minute : minute}`);
      
      temperatureData.push(item.temperature);
      humidityData.push(item.humidity);
      co2Data.push(item['gas(CO2)']);
    });
    
    this.setData({
      temperatureData: temperatureData,
      humidityData: humidityData,
      co2Data: co2Data,
      timeLabels: timeLabels
    });
    
    console.log('处理后的数据长度:', temperatureData.length);
    
    // 绘制图表
    this.drawTemperatureChart();
    this.drawHumidityChart();
    this.drawCO2Chart();
  },
  

  drawTemperatureChart: function() {
    const ctx = wx.createCanvasContext('temperatureChart');
    const { temperatureData, timeLabels } = this.data;
    const systemInfo = wx.getSystemInfoSync();
    const canvasWidth = systemInfo.windowWidth - 40; // 适配不同屏幕宽度
    
    // 绘制图表背景
    ctx.fillStyle = '#f5f5f5';
    ctx.fillRect(0, 0, canvasWidth, 300);
    
    // 绘制坐标轴
    const marginLeft = 50;
    const marginBottom = 50;
    const chartWidth = canvasWidth - marginLeft;
    const chartHeight = 200; // 图表实际绘制高度
    
    ctx.strokeStyle = '#999';
    ctx.beginPath();
    ctx.moveTo(marginLeft, chartHeight);
    ctx.lineTo(canvasWidth, chartHeight); // x轴
    ctx.moveTo(marginLeft, chartHeight);
    ctx.lineTo(marginLeft, 50); // y轴
    ctx.stroke();
    
    // 绘制y轴刻度 - 温度范围0-30度
    const yScale = chartHeight / 30; // 每度对应的像素
    for (let i = 0; i <= 3; i++) {
      const value = i * 10;
      const y = chartHeight - value * yScale;
      ctx.beginPath();
      ctx.moveTo(marginLeft - 5, y);
      ctx.lineTo(marginLeft, y);
      ctx.stroke();
      
      ctx.fillStyle = '#666';
      ctx.font = '12px Arial';
      ctx.fillText(value.toString(), marginLeft - 20, y + 4);
    }
    
    // 绘制x轴刻度
    const xStep = chartWidth / (timeLabels.length > 1 ? timeLabels.length - 1 : 1);
    timeLabels.forEach((label, index) => {
      const x = marginLeft + index * xStep;
      ctx.beginPath();
      ctx.moveTo(x, chartHeight);
      ctx.lineTo(x, chartHeight + 5);
      ctx.stroke();
      
      ctx.fillStyle = '#666';
      ctx.font = '12px Arial';
      ctx.fillText(label, x - 10, chartHeight + 25);
    });
    
    // 绘制温度曲线
    ctx.strokeStyle = '#ff6b6b';
    ctx.beginPath();
    ctx.moveTo(marginLeft, chartHeight - temperatureData[0] * yScale);
    
    temperatureData.forEach((temp, index) => {
      const x = marginLeft + index * xStep;
      const y = chartHeight - temp * yScale;
      ctx.lineTo(x, y);
    });
    
    ctx.stroke();
    
    // 绘制温度点
    ctx.fillStyle = '#ff6b6b';
    temperatureData.forEach((temp, index) => {
      const x = marginLeft + index * xStep;
      const y = chartHeight - temp * yScale;
      ctx.beginPath();
      ctx.arc(x, y, 5, 0, Math.PI * 2);
      ctx.fill();
    });
    
    ctx.draw();
  },

  drawHumidityChart: function() {
    const ctx = wx.createCanvasContext('humidityChart');
    const { humidityData, timeLabels } = this.data;
    const systemInfo = wx.getSystemInfoSync();
    const canvasWidth = systemInfo.windowWidth - 40;
    
    // 绘制图表背景
    ctx.fillStyle = '#f5f5f5';
    ctx.fillRect(0, 0, canvasWidth, 300);
    
    const marginLeft = 50;
    const marginBottom = 50;
    const chartWidth = canvasWidth - marginLeft;
    const chartHeight = 200;
    
    ctx.strokeStyle = '#999';
    ctx.beginPath();
    ctx.moveTo(marginLeft, chartHeight);
    ctx.lineTo(canvasWidth, chartHeight); // x轴
    ctx.moveTo(marginLeft, chartHeight);
    ctx.lineTo(marginLeft, 50); // y轴
    ctx.stroke();
    
    // 绘制y轴刻度 - 湿度范围0-100%
    const yScale = chartHeight / 100;
    for (let i = 0; i <= 5; i++) {
      const value = i * 20;
      const y = chartHeight - value * yScale;
      ctx.beginPath();
      ctx.moveTo(marginLeft - 5, y);
      ctx.lineTo(marginLeft, y);
      ctx.stroke();
      
      ctx.fillStyle = '#666';
      ctx.font = '12px Arial';
      ctx.fillText(value.toString() + '%', marginLeft - 20, y + 4);
    }
    
    // 绘制x轴刻度
    const xStep = chartWidth / (timeLabels.length > 1 ? timeLabels.length - 1 : 1);
    timeLabels.forEach((label, index) => {
      const x = marginLeft + index * xStep;
      ctx.beginPath();
      ctx.moveTo(x, chartHeight);
      ctx.lineTo(x, chartHeight + 5);
      ctx.stroke();
      
      ctx.fillStyle = '#666';
      ctx.font = '12px Arial';
      ctx.fillText(label, x - 10, chartHeight + 25);
    });
    
    // 绘制湿度曲线
    ctx.strokeStyle = '#4ECDC4';
    ctx.beginPath();
    ctx.moveTo(marginLeft, chartHeight - humidityData[0] * yScale);
    
    humidityData.forEach((humidity, index) => {
      const x = marginLeft + index * xStep;
      const y = chartHeight - humidity * yScale;
      ctx.lineTo(x, y);
    });
    
    ctx.stroke();
    
    // 绘制湿度点
    ctx.fillStyle = '#4ECDC4';
    humidityData.forEach((humidity, index) => {
      const x = marginLeft + index * xStep;
      const y = chartHeight - humidity * yScale;
      ctx.beginPath();
      ctx.arc(x, y, 5, 0, Math.PI * 2);
      ctx.fill();
    });
    
    ctx.draw();
  },

  drawCO2Chart: function() {
    const ctx = wx.createCanvasContext('co2Chart');
    const { co2Data, timeLabels } = this.data;
    const systemInfo = wx.getSystemInfoSync();
    const canvasWidth = systemInfo.windowWidth - 40;
    
    // 绘制图表背景
    ctx.fillStyle = '#f5f5f5';
    ctx.fillRect(0, 0, canvasWidth, 300);
    
    const marginLeft = 50;
    const marginBottom = 50;
    const chartWidth = canvasWidth - marginLeft;
    const chartHeight = 200;
    
    ctx.strokeStyle = '#999';
    ctx.beginPath();
    ctx.moveTo(marginLeft, chartHeight);
    ctx.lineTo(canvasWidth, chartHeight); // x轴
    ctx.moveTo(marginLeft, chartHeight);
    ctx.lineTo(marginLeft, 50); // y轴
    ctx.stroke();
    
    // 绘制y轴刻度 - 二氧化碳范围0-1500ppm
    const yScale = chartHeight / 1500;
    for (let i = 0; i <= 3; i++) {
      const value = i * 500;
      const y = chartHeight - value * yScale;
      ctx.beginPath();
      ctx.moveTo(marginLeft - 5, y);
      ctx.lineTo(marginLeft, y);
      ctx.stroke();
      
      ctx.fillStyle = '#666';
      ctx.font = '12px Arial';
      ctx.fillText(value.toString() + 'ppm', marginLeft - 20, y + 4);
    }
    
    // 绘制x轴刻度
    const xStep = chartWidth / (timeLabels.length > 1 ? timeLabels.length - 1 : 1);
    timeLabels.forEach((label, index) => {
      const x = marginLeft + index * xStep;
      ctx.beginPath();
      ctx.moveTo(x, chartHeight);
      ctx.lineTo(x, chartHeight + 5);
      ctx.stroke();
      
      ctx.fillStyle = '#666';
      ctx.font = '12px Arial';
      ctx.fillText(label, x - 10, chartHeight + 25);
    });
    
    // 绘制CO2曲线
    ctx.strokeStyle = '#FFD166';
    ctx.beginPath();
    ctx.moveTo(marginLeft, chartHeight - co2Data[0] * yScale);
    
    co2Data.forEach((co2, index) => {
      const x = marginLeft + index * xStep;
      const y = chartHeight - co2 * yScale;
      ctx.lineTo(x, y);
    });
    
    ctx.stroke();
    
    // 绘制CO2点
    ctx.fillStyle = '#FFD166';
    co2Data.forEach((co2, index) => {
      const x = marginLeft + index * xStep;
      const y = chartHeight - co2 * yScale;
      ctx.beginPath();
      ctx.arc(x, y, 5, 0, Math.PI * 2);
      ctx.fill();
    });
    
    ctx.draw();
  },
    
  generateAdvice: function() {
    // 生成AI建议 - 实际项目中调用云函数
    this.generateAIDataAdvice();
    this.generatePredictionAdvice();
  },
    
  generateAIDataAdvice: function() {
    // 模拟调用云函数获取AI建议
    // 实际项目中应使用 wx.cloud.callFunction 调用blueLM-70B云函数
    
    // 从本地数据生成建议
    const { temperatureData, humidityData, co2Data } = this.data;
    const avgTemp = temperatureData.reduce((sum, val) => sum + val, 0) / temperatureData.length;
    const avgHumidity = humidityData.reduce((sum, val) => sum + val, 0) / humidityData.length;
    const avgCO2 = co2Data.reduce((sum, val) => sum + val, 0) / co2Data.length;
    
    let advice = "AI建议:\n\n";
    
    // 根据数据生成建议
    if (avgTemp < 10) {
      advice += "1. 温度较低，建议开启加热设备以保持适宜温度。\n";
    } else if (avgTemp > 25) {
      advice += "1. 温度较高，建议开启通风设备降低温度。\n";
    } else {
      advice += "1. 温度适宜，可保持当前环境。\n";
    }
    
    if (avgHumidity < 40) {
      advice += "2. 湿度较低，建议开启加湿器增加空气湿度。\n";
    } else if (avgHumidity > 70) {
      advice += "2. 湿度较高，建议开启通风扇降低湿度，减少病害发生可能性。\n";
    } else {
      advice += "2. 湿度适宜，无需额外操作。\n";
    }
    
    if (avgCO2 < 600) {
      advice += "3. 二氧化碳浓度较低，建议补充二氧化碳以促进植物光合作用。\n";
    } else if (avgCO2 > 1000) {
      advice += "3. 二氧化碳浓度较高，建议加强通风以降低浓度。\n";
    } else {
      advice += "3. 二氧化碳浓度适宜，保持当前状态。\n";
    }
    
    advice += "\n根据您提供的条件,以下是建议的措施:\n" +
              "1. 打开通风扇: 由于温度" + (avgTemp < 15 ? "较低" : "适中") + ", 湿度" + (avgHumidity < 40 ? "较低" : avgHumidity > 60 ? "较高" : "适宜") + ", 打开通风扇可以帮助空气流通, 减少病害发生的可能性。\n" +
              "2. 打开棚顶: 这可以帮助调节温度和湿度, 增加空气流通。\n" +
              "3. 不需要打开日光灯: 光照强度已经足够, 不需要额外补光。";
    
    this.setData({
      aiAdvice: advice,
      adviceLoaded: true
    });
  },
    
  generatePredictionAdvice: function() {
    // 生成未来趋势预测 - 实际项目中结合天气API和历史数据
    const { temperatureData, humidityData, co2Data } = this.data;
    const lastTemp = temperatureData[temperatureData.length - 1];
    const lastHumidity = humidityData[humidityData.length - 1];
    const lastCO2 = co2Data[co2Data.length - 1];
    
    let prediction = "未来趋势预测与建议:\n\n";
    
    // 简单趋势预测逻辑
    if (temperatureData.length > 2) {
      const tempTrend = temperatureData[temperatureData.length - 1] - temperatureData[temperatureData.length - 2];
      if (tempTrend > 2) {
        prediction += "1. 温度呈上升趋势，预计未来12小时温度可能继续升高" + (tempTrend > 5 ? "较多" : "2-3度") + "，请注意通风降温。\n";
      } else if (tempTrend < -2) {
        prediction += "1. 温度呈下降趋势，预计未来12小时温度可能继续降低" + (tempTrend < -5 ? "较多" : "2-3度") + "，请注意保温。\n";
      } else {
        prediction += "1. 温度趋势平稳，保持当前管理即可。\n";
      }
    } else {
      prediction += "1. 温度数据不足，无法准确预测趋势，请持续监测。\n";
    }
    
    if (humidityData.length > 2) {
      const humidityTrend = humidityData[humidityData.length - 1] - humidityData[humidityData.length - 2];
      if (humidityTrend > 5) {
        prediction += "2. 湿度呈上升趋势，预计未来12小时湿度可能继续升高" + (humidityTrend > 10 ? "较多" : "5-10%") + "，请注意通风降湿。\n";
      } else if (humidityTrend < -5) {
        prediction += "2. 湿度呈下降趋势，预计未来12小时湿度可能继续降低" + (humidityTrend < -10 ? "较多" : "5-10%") + "，请注意适当补水。\n";
      } else {
        prediction += "2. 湿度趋势平稳，保持当前管理即可。\n";
      }
    } else {
      prediction += "2. 湿度数据不足，无法准确预测趋势，请持续监测。\n";
    }
    
    if (co2Data.length > 2) {
      const co2Trend = co2Data[co2Data.length - 1] - co2Data[co2Data.length - 2];
      if (co2Trend > 100) {
        prediction += "3. 二氧化碳浓度呈上升趋势，预计未来12小时浓度可能继续升高" + (co2Trend > 200 ? "较多" : "50-100ppm") + "，若浓度过高请及时通风。\n";
      } else if (co2Trend < -100) {
        prediction += "3. 二氧化碳浓度呈下降趋势，预计未来12小时浓度可能继续降低" + (co2Trend < -200 ? "较多" : "50-100ppm") + "，建议考虑补充二氧化碳。\n";
      } else {
        prediction += "3. 二氧化碳浓度趋势平稳，保持当前管理即可。\n";
      }
    } else {
      prediction += "3. 二氧化碳数据不足，无法准确预测趋势，请持续监测。\n";
    }
    
    prediction += "\n未来一天作业建议:\n" +
                  "1. 建议在" + (lastTemp > 20 ? "上午" : "下午") + "进行通风，保持温室内空气流通。\n" +
                  "2. 若湿度低于" + (lastHumidity < 40 ? "40%" : "50%") + "，建议在" + (lastHumidity < 30 ? "早晨" : "傍晚") + "进行喷雾增湿。\n" +
                  "3. 密切关注二氧化碳浓度变化，" + (lastCO2 < 600 ? "可考虑使用二氧化碳发生器" : "若浓度高于1000ppm请及时通风") + "。";
    
    this.setData({
      predictionAdvice: prediction,
      predictionLoaded: true
    });
  }
});